import {defineStore} from 'pinia'
import {login, logout, userInfo} from "@/api/login";
import cache from '@/utils/cache'
import {CacheEnum} from "@/enums/cacheEnum";
import router, {filterRoutes} from "@/router";
import Cache from "@/utils/cache";
import {clearAll} from "@/utils/auth";
import {PageEnum} from "@/enums/pageEnum";


const useUserStore = defineStore({
    id: 'user',
    state: () => {
        return {
            token: Cache.get(CacheEnum.TOKEN_KEY) || '',
            // 用户信息
            userInfo: {},
            // 路由
            routes: [],
            // 菜单
            menu: [],
            // 权限
            perms: []
        }
    },
    actions: {
        reset() {
            this.token = ''
            this.userInfo = {}
            this.perms = []
        },
        login(params) {
            const {account, password} = params
            return new Promise((resolve, reject) => {
                login({account: account, password: password})
                    .then((data) => {
                        this.token = data.token
                        cache.set(CacheEnum.TOKEN_KEY, data.token)
                        resolve(data)
                    })
                    .catch((err) => {
                        reject(err)
                    })
            })
        },
        logout() {
            return new Promise((resolve, reject) => {
                logout()
                    .then(async (data) => {
                        this.token = ''
                        await router.push(PageEnum.LOGIN)
                        clearAll()
                        resolve(data)
                    })
                    .catch((err) => {
                        reject(err)
                    })
            })
        },
        getUserInfo() {
            return new Promise((resolve, reject) => {
                userInfo()
                    .then((data) => {
                        this.userInfo = data.user;
                        this.menu = data.menu;
                        this.perms = data.perms;
                        this.routes = filterRoutes(data.menu);
                        resolve(data)
                    })
                    .catch((err) => {
                        reject(err)
                    })
            })
        },
    }
})

export default useUserStore